package com.rongkang.interview.jvm.quote;

import java.lang.ref.SoftReference;

/**
 * @Description:
 * @author: 荣康
 * @date: 2021/12/16
 * 软引用  在发生GC的时候,如果内存够用，软引用就不会被回收  如果内存不够用，软引用引用的对象就会被回收
 */
public class SoftReferenceDemo {
    public static void main(String[] args) {
        softReferenceNoGC();
        softReferenceGC();

    }
    private static void softReferenceNoGC() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println("o1 = " + o1);
        System.out.println("softReference = " + softReference.get());
        o1 = null;
        System.gc();
        System.out.println("o1 = " + o1);
        System.out.println("softReference = " + softReference.get());
    }

    private static void softReferenceGC() {
        //这里更改内存参数 -Xms5m -Xmx5m -XX:+PrintGCDetails
        //此时内存溢出，内存不够用，会将软引用清除
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println("o1 = " + o1);
        System.out.println("softReference = " + softReference.get());
        o1 = null;
       try {
           byte [] bytes = new byte[30*1024*1024];
       }finally {
           System.out.println("o1 = " + o1);
           System.out.println("softReference = " + softReference.get());
       }

    }
}
